import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.border.EmptyBorder;

import org.json.JSONException;
import org.json.JSONObject;

public class GlobalsNewMain extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Connection connection;
	private InteractionGlobalsBD news;
	private JPanel contentPane;
	private JTextField showTopic;
	private JTextField showTitle;
	private JTextArea showContent;
	private JLabel lblStatusbar;
	private JLabel status;
	private static int count = 0;
	private static boolean statusConnection = false;
	private int numberSearch = 0;
	private int numberShowNews = 0;
	private JTextField numbernew;
	private JTextField addTopic;
	private JTextField addTitle;
	private JTextArea addContent;
	private JButton btnShowRandom;
	private SpringLayout sl_contentPane;
	private JButton btnSearch;
	private JButton btnShowPrevious;
	private JButton btnShowNext;
	private JRadioButtonMenuItem statusFavorite;
	private JTextField countNews;
	private JTextField time;
	private JTextField period;
	private HashMap< Integer,  Integer> keyMap = new HashMap< Integer,  Integer>();
	private final static Timer timer = new Timer();
	private int numberOfNews = 0;
	private int counterNews = 0;
	private Notification panel;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					GlobalsNewMain frame = new GlobalsNewMain();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	private GlobalsNewMain() {
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 667, 515);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		sl_contentPane = new SpringLayout();
		contentPane.setLayout(sl_contentPane);
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnGlobals = new JMenu("Globals");
		menuBar.add(mnGlobals);

		JMenuItem mntmConnect = new JMenuItem("Connect");
		mntmConnect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (statusConnection == false) {
					connection = new Connection();
					connection.connect();
					news = connection.getKeyValueMap("news");
					statusConnection = true;
					status.setText("The base is connected");
				}
			}
		});
		mnGlobals.add(mntmConnect);

		JMenuItem mntmClose = new JMenuItem("Disconnect");
		mntmClose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (statusConnection == true) {
					statusConnection = false;
					news.clear();
					connection.close();
					status.setText("Database is not connected");
				}
			}
		});
		mnGlobals.add(mntmClose);

		JMenu mnAs = new JMenu("Add news");
		menuBar.add(mnAs);

		JMenuItem mntmAddnews = new JMenuItem("Add new");
		mntmAddnews.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (statusConnection == true) {
					remove();
					frameworkLabel(40, 50, "Topic:", "Title:", "Content:");
					frameworkButton(40, 50);
					JButton btnAddnews = new JButton("Add new");
					status.setText("Please add some news");
					btnAddnews.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent arg0) {
							ArrayList<String> dataList = new ArrayList<String>();
							if (addTopic.getText().equals("")
									|| addTitle.getText().equals("")
									|| addContent.getText().equals("")) {
								status.setText("Fill the fields");
							} else {
								dataList.add(addTopic.getText());
								dataList.add(addTitle.getText());
								dataList.add(addContent.getText());
								news.store(count, dataList);
								keyMap.put(count, 0);
								count++;
								status.setText("new's number:" + count
										+ " entered into the database");
							}
						}

					});
					sl_contentPane.putConstraint(SpringLayout.WEST, btnAddnews,
							100, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH,
							btnAddnews, 330, SpringLayout.NORTH, contentPane);
					contentPane.add(btnAddnews);
					setContentPane(contentPane);
				} else {
					status.setText("Connect to base");
				}
			}
		});
		mnAs.add(mntmAddnews);

		JMenuItem mntmAddFromIcndb = new JMenuItem("Add from ICNDB");
		mntmAddFromIcndb.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (statusConnection == true) {
					new JsonReader();
					for (int i = 0; i < 15; i++) {
						try {
							ArrayList<String> dataList = new ArrayList<String>();
							JSONObject json = JsonReader
									.readJsonFromUrl("http://api.icndb.com/jokes/random");
							JSONObject json1 = new JSONObject(json.get("value")
									.toString().replace(":", ": ")
									.replace("}", " }").replace("{", "{ ")
									.replace(",", ", "));
							dataList.add("Chuck Norris");
							dataList.add("joke");
							dataList.add(json1.get("joke").toString());
							keyMap.put(count, 0);
							news.store(count, dataList);
							count++;
						} catch (IOException e) {
							e.printStackTrace();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
					status.setText("Joke's from ICNDB download");
				} else {
					status.setText("Connect to base");
				}
			}
		});
		mnAs.add(mntmAddFromIcndb);

		JMenu mnShow = new JMenu("Show");
		menuBar.add(mnShow);

		JMenuItem mntmRandom = new JMenuItem("Random");
		mntmRandom.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (statusConnection == true) {
					remove();
					frameworkLabel(40, 50, "Topic:", "Title:", "Content:");
					frameworkButton(40, 50);
					status.setText("Random news");
					addTitle.setEditable(false);
					addTopic.setEditable(false);
					addContent.setEditable(false);
					JButton like = new JButton("like");
					sl_contentPane.putConstraint(SpringLayout.WEST, like, 350,
							SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH, like, 100,
							SpringLayout.NORTH, contentPane);
					like.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
								keyMap.put(numberShowNews, 1);
						}
					});
					contentPane.add(like);
					JButton dislike = new JButton("dislike");
					sl_contentPane.putConstraint(SpringLayout.WEST, dislike,
							350, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH, dislike,
							150, SpringLayout.NORTH, contentPane);
					dislike.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
								keyMap.put(numberShowNews, -1);
							}
					});
					contentPane.add(dislike);
					if (count > 0) {
						Random rnd = new Random(new Date().getTime());
						ArrayList<String> value = news.load(rnd.nextInt(count));
						addTitle.setText(value.get(0));
						addTopic.setText(value.get(1));
						addContent.setText(value.get(2));
					} else {
						status.setText("No news in Database");
					}
					btnShowRandom = new JButton("Next");
					btnShowRandom.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							if (count > 0) {
								Random rnd = new Random(new Date().getTime());
								numberShowNews = rnd.nextInt(count);
								if (statusFavorite.isSelected() == true) {
									for (numberShowNews = 0; numberShowNews<count;numberShowNews++)
										if (keyMap.get(numberShowNews) == 1) {
											break;
										}
								}
								ArrayList<String> value = news
										.load(numberShowNews);
								addTopic.setText(value.get(0));
								addTitle.setText(value.get(1));
								addContent.setText(value.get(2));
								} else {
								status.setText("No news in Database");
							}
						}
					});
					sl_contentPane.putConstraint(SpringLayout.WEST,
							btnShowRandom, 100, SpringLayout.WEST, contentPane);
					sl_contentPane
							.putConstraint(SpringLayout.NORTH, btnShowRandom,
									330, SpringLayout.NORTH, contentPane);
					contentPane.add(btnShowRandom);
					setContentPane(contentPane);
				} else {
					status.setText("connect to base");
				}
			}

		});
		mnShow.add(mntmRandom);

		JMenuItem mntmByNumber = new JMenuItem("By number");
		mntmByNumber.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (statusConnection == true) {
					remove();
					frameworkLabel(40, 50, "Topic:", "Title:", "Content:");
					frameworkButton(40, 50);
					status.setText("Please put the number of new");
					addTitle.setEditable(false);
					addTopic.setEditable(false);
					addContent.setEditable(false);
					numbernew = new JTextField();
					sl_contentPane.putConstraint(SpringLayout.WEST, numbernew,
							200, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH, numbernew,
							330, SpringLayout.NORTH, contentPane);
					numbernew.setColumns(3);
					contentPane.add(numbernew);
					JButton btnShownews = new JButton("Show");
					sl_contentPane.putConstraint(SpringLayout.WEST,
							btnShownews, 100, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH,
							btnShownews, 330, SpringLayout.NORTH, contentPane);
					btnShownews.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent arg0) {
							if (numbernew.getText().equals("")) {
								status.setText("Fill the fields");
							} else {
								if (numbernew.getText().matches("^-?\\d+$")) {
									int number = Integer.parseInt(numbernew
											.getText());
									if (count > 0 && number <= count
											&& number > 0) {
										number--;
										ArrayList<String> value = news
												.load(number);
										addTitle.setText(value.get(0));
										addTopic.setText(value.get(1));
										addContent.setText(value.get(2));
										status.setText("new number:"
												+ numbernew.getText());
									} else {
										status.setText("This new is not in the database");
									}
								} else {
									status.setText("Date error");
								}
							}
						}
					});
					contentPane.add(btnShownews);
					setContentPane(contentPane);
				} else {
					status.setText("connect to base");
				}
			}
		});
		mnShow.add(mntmByNumber);
		// rdbtnmntmFavorite.isSelected()
		statusFavorite = new JRadioButtonMenuItem("Show favorite new");
		mnShow.add(statusFavorite);

		JMenu mnSearch = new JMenu("Search");
		menuBar.add(mnSearch);

		JMenuItem mntmSearch = new JMenuItem("Search");
		mntmSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (statusConnection == true) {
					remove();
					frameworkLabel(40, 50, "Topic:", "Title:", "Content:");
					frameworkLabel(340, 50, "Topic:", "Title:", "Content:");
					frameworkButton(40, 50);
					showTopic = new JTextField();
					sl_contentPane.putConstraint(SpringLayout.WEST, showTopic,
							400, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH, showTopic,
							50, SpringLayout.NORTH, contentPane);
					showTopic.setColumns(15);
					showTopic.setEditable(false);
					contentPane.add(showTopic);

					showTitle = new JTextField();
					sl_contentPane.putConstraint(SpringLayout.WEST, showTitle,
							400, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH, showTitle,
							90, SpringLayout.NORTH, contentPane);
					showTitle.setEditable(false);
					contentPane.add(showTitle);
					showTitle.setColumns(15);

					showContent = new JTextArea();
					sl_contentPane.putConstraint(SpringLayout.WEST,
							showContent, 400, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH,
							showContent, 130, SpringLayout.NORTH, contentPane);
					showContent.setEditable(false);
					showContent.setRows(10);
					showContent.setColumns(20);
					showContent.setLineWrap(true);
					contentPane.add(showContent);

					btnSearch = new JButton("Search");
					sl_contentPane.putConstraint(SpringLayout.WEST, btnSearch,
							120, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH, btnSearch,
							330, SpringLayout.NORTH, contentPane);
					contentPane.add(btnSearch);
					btnShowPrevious = new JButton("Show Previous");
					sl_contentPane
							.putConstraint(SpringLayout.WEST, btnShowPrevious,
									20, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH,
							btnShowPrevious, 370, SpringLayout.NORTH,
							contentPane);
					contentPane.add(btnShowPrevious);
					btnShowPrevious.setEnabled(false);
					btnShowNext = new JButton("Show Next");
					sl_contentPane.putConstraint(SpringLayout.WEST,
							btnShowNext, 170, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH,
							btnShowNext, 370, SpringLayout.NORTH, contentPane);
					btnShowNext.setEnabled(false);
					contentPane.add(btnShowNext);
					setContentPane(contentPane);
					btnSearch.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							if (count > 0) {
								numberSearch = 0;
								btnShowPrevious.setEnabled(true);
								btnShowNext.setEnabled(true);
								while (numberSearch < count) {
									ArrayList<String> value = news
											.load(numberSearch);
									if (value.get(0).contains(
											addTopic.getText())
											&& value.get(1).contains(
													addTitle.getText())
											&& value.get(2).contains(
													addContent.getText())) {
										showTopic.setText(value.get(0));
										showTitle.setText(value.get(1));
										showContent.setText(value.get(2));
										setContentPane(contentPane);
										numberSearch++;
										break;

									}
									numberSearch++;
									if (numberSearch == count) {
										showTopic.setText("");
										showTitle.setText("");
										showContent.setText("");
										status.setText("No such elements in database");
									}
								}
							} else {
								status.setText("No elements in database");
							}
						}
					});
					btnShowPrevious.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							while (numberSearch < count) {
								ArrayList<String> value = news
										.load(numberSearch);
								if (value.get(0).contains(addTopic.getText())
										&& value.get(1).contains(
												addTitle.getText())
										&& value.get(2).contains(
												addContent.getText())) {
									showTopic.setText(value.get(0));
									showTitle.setText(value.get(1));
									showContent.setText(value.get(2));
									setContentPane(contentPane);
									numberSearch++;
									break;

								}
								numberSearch++;
								if (numberSearch == count) {
									showTopic.setText("");
									showTitle.setText("");
									showContent.setText("");
									status.setText("No such elements in database");

								}
							}
						}
					});
					btnShowNext.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent e) {
							while (numberSearch > 0) {
								ArrayList<String> value = news
										.load(numberSearch);
								if (value.get(0).contains(addTopic.getText())
										&& value.get(1).contains(
												addTitle.getText())
										&& value.get(2).contains(
												addContent.getText())) {
									showTopic.setText(value.get(0));
									showTitle.setText(value.get(1));
									showContent.setText(value.get(2));
									setContentPane(contentPane);
									numberSearch--;
									break;

								}
								numberSearch--;
								if (numberSearch == 0) {
									showTopic.setText("");
									showTitle.setText("");
									showContent.setText("");
									status.setText("No such elements in database");

								}
							}

						}
					});
				} else {
					status.setText("connect to base");
				}
			}
		});
		mnSearch.add(mntmSearch);

		JMenu mnTaskList = new JMenu("Task list");
		menuBar.add(mnTaskList);

		JMenuItem mntmNewMenuItem = new JMenuItem("Timer");
		mntmNewMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (statusConnection == true) {
					remove();
					frameworkLabel(40, 50, "In what time?(minutes):", "How many news?:",
							"Period(second):");
					time = new JTextField();
					sl_contentPane.putConstraint(SpringLayout.WEST, time, 190,
							SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH, time, 50,
							SpringLayout.NORTH, contentPane);
					time.setColumns(5);
					contentPane.add(time);

					countNews = new JTextField();
					sl_contentPane.putConstraint(SpringLayout.WEST, countNews,
							190, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH, countNews,
							90, SpringLayout.NORTH, contentPane);
					countNews.setColumns(5);
					contentPane.add(countNews);

					period = new JTextField();
					sl_contentPane.putConstraint(SpringLayout.WEST, period,
							190, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH, period,
							130, SpringLayout.NORTH, contentPane);
					period.setColumns(5);
					contentPane.add(period);
					JButton btnApply = new JButton("Apply");
					sl_contentPane.putConstraint(SpringLayout.WEST, btnApply,
							100, SpringLayout.WEST, contentPane);
					sl_contentPane.putConstraint(SpringLayout.NORTH, btnApply,
							180, SpringLayout.NORTH, contentPane);
					btnApply.addActionListener(new ActionListener() {
						public void actionPerformed(ActionEvent arg0) {
							if (countNews.getText().equals("")
									&& period.getText().equals("")
									&& time.getText().equals("")) {
								status.setText("Fill the fields");
							} else {
								if (countNews.getText().matches("^-?\\d+$")
										&& period.getText().matches("^-?\\d+$")
										&& time.getText().matches("^-?\\d+$")) {
									numberOfNews = Integer.parseInt(countNews	
											.getText());
									int number1 = Integer.parseInt(period
											.getText());
									int number2 = Integer.parseInt(time
											.getText());
									counterNews = 0;
									panel = new Notification();
									Timer timer = new Timer();
									remove();
									frameworkLabel(40, 50, "Topic:", "Title:", "Content:");
									frameworkButton(40, 50);
									timer.schedule ( new ToDoTask (  ) , number2*1000, number1*1000 ) ;
								} else {
									status.setText("Date error");
								}
							}
						}
					});
					contentPane.add(btnApply);
				} else {
					status.setText("connect to base");
				}
				setContentPane(contentPane);
			}
		});
		mnTaskList.add(mntmNewMenuItem);

		lblStatusbar = new JLabel("StatusBar:");
		sl_contentPane.putConstraint(SpringLayout.NORTH, lblStatusbar, 0,
				SpringLayout.NORTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.WEST, lblStatusbar, 231,
				SpringLayout.WEST, contentPane);
		contentPane.add(lblStatusbar);

		status = new JLabel("");
		sl_contentPane.putConstraint(SpringLayout.NORTH, status, 20,
				SpringLayout.NORTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.WEST, status, 220,
				SpringLayout.WEST, contentPane);
		contentPane.add(status);

	}

	void frameworkLabel(int left, int right, String nameFirst,
			String nameSecond, String nameThird) {
		JLabel label = new JLabel(nameFirst);
		sl_contentPane.putConstraint(SpringLayout.WEST, label, left,
				SpringLayout.WEST, contentPane);
		sl_contentPane.putConstraint(SpringLayout.NORTH, label, right,
				SpringLayout.NORTH, contentPane);
		contentPane.add(label);

		JLabel label_1 = new JLabel(nameSecond);
		sl_contentPane.putConstraint(SpringLayout.WEST, label_1, left,
				SpringLayout.WEST, contentPane);
		sl_contentPane.putConstraint(SpringLayout.NORTH, label_1, right + 40,
				SpringLayout.NORTH, contentPane);
		contentPane.add(label_1);

		JLabel label_2 = new JLabel(nameThird);
		sl_contentPane.putConstraint(SpringLayout.WEST, label_2, left,
				SpringLayout.WEST, contentPane);
		sl_contentPane.putConstraint(SpringLayout.NORTH, label_2, right + 80,
				SpringLayout.NORTH, contentPane);
		contentPane.add(label_2);
	}

	void frameworkButton(int left, int right) {
		addTopic = new JTextField();
		sl_contentPane.putConstraint(SpringLayout.WEST, addTopic, left + 60,
				SpringLayout.WEST, contentPane);
		sl_contentPane.putConstraint(SpringLayout.NORTH, addTopic, right,
				SpringLayout.NORTH, contentPane);
		addTopic.setColumns(15);
		contentPane.add(addTopic);

		addTitle = new JTextField();
		sl_contentPane.putConstraint(SpringLayout.WEST, addTitle, left + 60,
				SpringLayout.WEST, contentPane);
		sl_contentPane.putConstraint(SpringLayout.NORTH, addTitle, right + 40,
				SpringLayout.NORTH, contentPane);
		addTitle.setColumns(15);
		contentPane.add(addTitle);

		addContent = new JTextArea();
		sl_contentPane.putConstraint(SpringLayout.WEST, addContent, left + 60,
				SpringLayout.WEST, contentPane);
		sl_contentPane.putConstraint(SpringLayout.NORTH, addContent,
				right + 80, SpringLayout.NORTH, contentPane);
		addContent.setRows(10);
		addContent.setColumns(20);
		addContent.setLineWrap(true);
		contentPane.add(addContent);
	}

	void remove() {
		int i = 0;
		while (i < contentPane.getComponentCount()) {
			if ((contentPane.getComponent(i) instanceof JButton)
					|| (contentPane.getComponent(i) instanceof JTextField)
					|| (contentPane.getComponent(i) instanceof JTextArea)
					|| ((contentPane.getComponent(i) instanceof JLabel)
							&& !(contentPane.getComponent(i)
									.equals(lblStatusbar)) && !(contentPane
								.getComponent(i).equals(status)))) {
				contentPane.remove(i);
				i--;
			}
			i++;
		}
		setContentPane(contentPane);
	}
	class ToDoTask extends TimerTask  {
	    public void run (  )   {
	    	if (count > 0) {
	    		counterNews++;
				status.setText("Random news");
				addTitle.setEditable(false);
				addTopic.setEditable(false);
				addContent.setEditable(false);
				Random rnd = new Random(new Date().getTime());
				numberShowNews = rnd.nextInt(count);
				if (statusFavorite.isSelected() == true) {
					for (numberShowNews = 0; numberShowNews<count;numberShowNews++)
						if (keyMap.get(numberShowNews) == 1) {
							break;
						}
				}
				ArrayList<String> value = news
						.load(numberShowNews);
				addTopic.setText(value.get(0));
				addTitle.setText(value.get(1));
				addContent.setText(value.get(2));
				panel.setContent(value.get(2));
				keyMap.put(numberShowNews, Notification.getImpression());
				if (counterNews == numberOfNews) {
					cancel ();
	    	        timer.cancel();
			      }
				} else {
				status.setText("No news in Database");
			}
	    }
	  }
}
